package cn.tedu.mall.product.service.impl;

import cn.tedu.mall.common.exception.CoolSharkServiceException;
import cn.tedu.mall.common.pojo.product.dto.AlbumAddNewDTO;
import cn.tedu.mall.common.pojo.product.dto.AlbumUpdateDTO;
import cn.tedu.mall.common.pojo.product.model.Album;
import cn.tedu.mall.common.pojo.product.vo.AlbumStandardVO;
import cn.tedu.mall.common.restful.JsonPage;
import cn.tedu.mall.common.restful.ResponseCode;
import cn.tedu.mall.product.constant.DataCommonConst;
import cn.tedu.mall.product.mapper.AlbumMapper;
import cn.tedu.mall.product.mapper.PictureMapper;
import cn.tedu.mall.product.mapper.SpuMapper;
import cn.tedu.mall.product.service.IAlbumService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class AlbumServiceImpl implements IAlbumService {
    @Autowired(required = false)
    private AlbumMapper albumMapper;
    @Autowired
    private PictureMapper pictureMapper;
    @Autowired
    private SpuMapper spuMapper;

    @Override public Long addNew(AlbumAddNewDTO albumAddnewDTO) {
        /**
         * 引入持久层 mapper 封装对象,写入数据库,新增相册成功
         * 对接数据库数据格式model DO
         */
        Album album=new Album();
        /**
         * 明显缺少 id和 创建修改时间
         */
        LocalDateTime now=LocalDateTime.now();
        BeanUtils.copyProperties(albumAddnewDTO,album);
        album.setGmtCreate(now);
        album.setGmtModified(now);
        /**
         * 使用返回值result 接收影响rows 作为新增新增成功返回1 ,新增失败返回0 这个是业务异常
         */
        int result=albumMapper.insert(album);
        if (result==0){
            //抛出业务异常,新增失败
            throw new CoolSharkServiceException(ResponseCode.BAD_REQUEST,"新增相册失败");
        }
        /**
         * 如果是数据库执行sql其他异常,SqlGramma等 抛出去
         */
        return album.getId();
    }

    @Override public void deleteById(Long id) {

        // 检查尝试删除的相册是否存在
        AlbumStandardVO result = albumMapper.getById(id);
        System.out.println(result);
        if (result == null) {
            throw new CoolSharkServiceException(ResponseCode.NOT_FOUND, "删除相册失败，尝试访问的数据不存在！");
        }

        // 检查此相册下是否包含图片
        int pictureCount = pictureMapper.countByAlbumId(id);
        if (pictureCount > 0) {
            throw new CoolSharkServiceException(ResponseCode.CONFLICT,
                    "删除相册失败，仍有图片关联到此相册，请先删除相关图片或解除关联后再次尝试！");
        }

        // 检查此相册是否已被关联到SPU
        int spuCount = spuMapper.countByAlbumId(id);
        if (spuCount > 0) {
            throw new CoolSharkServiceException(ResponseCode.CONFLICT,
                    "删除相册失败，此相册已被关联到SPU，请先删除相关SPU或解除关联后再次尝试！！");
        }

        // 执行删除

        int rows = albumMapper.deleteById(id);
        if (rows != 1) {
            throw new CoolSharkServiceException(ResponseCode.INTERNAL_SERVER_ERROR,
                    "删除相册失败，服务器忙，请稍后再次尝试！");
        }
    }

    @Override public void updateById(Long id, AlbumUpdateDTO albumUpdateDTO) {

        // 检查尝试更新的数据是否存在
        AlbumStandardVO currentAlbum = albumMapper.getById(id);
        if (currentAlbum == null) {
            throw new CoolSharkServiceException(ResponseCode.NOT_FOUND, "更新相册信息失败，尝试访问的数据不存在！");
        }

        // 检查新名称是否冲突
        String albumNewName = albumUpdateDTO.getName();
        AlbumStandardVO checkNameQueryResult = albumMapper.getByName(albumNewName);
        if (checkNameQueryResult != null && !checkNameQueryResult.getId().equals(id)) {
            throw new CoolSharkServiceException(ResponseCode.CONFLICT,
                    "更新相册信息失败，相册名称(" + albumNewName + ")已存在！");
        }

        // 执行更新
        Album album = new Album();
        BeanUtils.copyProperties(albumUpdateDTO, album);
        album.setId(id);
        album.setName(albumUpdateDTO.getName());
        album.setDescription(albumUpdateDTO.getDescription());
        album.setSort(
                albumUpdateDTO.getSort() == null ? DataCommonConst.SORT_DEFAULT : albumUpdateDTO.getSort());

        int rows = albumMapper.update(album);
        if (rows != 1) {
            throw new CoolSharkServiceException(ResponseCode.INTERNAL_SERVER_ERROR,
                    "更新相册信息失败，服务器忙，请稍后再次尝试！");
        }
    }

    @Override public AlbumStandardVO getById(Long id) {
        AlbumStandardVO albumStandardVO = albumMapper.getById(id);
        if (albumStandardVO == null) {
            throw new CoolSharkServiceException(ResponseCode.NOT_FOUND, "获取相册详情失败，尝试访问的数据不存在！");
        }
        return albumStandardVO;
    }

    @Override
    public JsonPage<AlbumStandardVO> list(Integer page, Integer pageSize) {
        PageHelper.startPage(page,pageSize);

        List<AlbumStandardVO> list = albumMapper.list();
        for (int i = 0; i <list.size() ; i++) {
           Integer  count= pictureMapper.countByAlbumId(list.get(i).getId());
           list.get(i).setPictureCount(count);
        }
        return JsonPage.restPage(new PageInfo<>(list));
    }
    @Override
    public JsonPage<AlbumStandardVO> list1(Integer page, Integer pageSize) {
        PageHelper.startPage(page,pageSize);
        List<AlbumStandardVO> list = albumMapper.list1();
        for (int i = 0; i <list.size() ; i++) {
            Integer  count= pictureMapper.countByAlbumId(list.get(i).getId());
            list.get(i).setPictureCount(count);
        }
        return JsonPage.restPage(new PageInfo<>(list));
    }
}
